// @ts-ignore
import { createRouter, createWebHistory,createWebHashHistory } from 'vue-router'
import axios from 'axios';

const mainRoutes = [
]

const subsetRoutes = [
  {
    path: '', name: "_main",meta: {title: '无界交互'},
    component: () => import('../views/main.vue'),
    children: [
      {path: '/singlePageA',name: "singlePageA",meta: {title: '单页A'},component: () => import('../views/singlePageA.vue')},
      {path: '/singlePageB',name: "singlePageB",meta: {title: '单页B'},component: () => import('../views/singlePageB.vue')},
      {path: '/survival',name: "survival",meta: {title: '保活状态'},component: () => import('../views/survival.vue')},
    ]
  },
  {path: '/singlePageBs',name: "singlePageBs",meta: {title: '单页B'},component: () => import('../views/singlePageB.vue')},


]

const  routes =   [...mainRoutes,...subsetRoutes]


const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),//带#
  // history: createWebHistory(import.meta.env.BASE_URL),//不带#  打包有问题
  routes
})





//路由跳转前拦截
router.beforeEach((to, from, next) => {

  next() // 跳转

  return false;
  /*
  * 1.有token  跳转
  * 2.没有 token 登录
  * 3.如果是登录  有 token 跳转 首页
  *
  *
  * */
  const token = sessionStorage.getItem('loginData');

  if(to.name == '_login'){
    if(!token){
      next() // 跳转
    }else{
      next({name: 'dataDisplay'}) // 跳转到登录页
    }
  }else{
    if (to.name == "error_401" || to.name == "error_500" || to.name == "error_404" ) {//首页 401 500 404 全部放过
      next()
    } else if (!token) {
      next({name: '_login'}) // 跳转到登录页
    } else {
      next()
    }
  }
})

//路由跳转后拦截
router.afterEach(async (to, from) => {
  if(process.env.NODE_ENV !== "development") {
    await axios.get('version.json').then((res)=>{
      if(res.status === 200) {
        let { version } = res.data
        let cocalVersion = localStorage.getItem('version_v')
        if(!cocalVersion || version !== cocalVersion) {
          localStorage.setItem('version_v', version)
          window.location.reload()
        }
      }
    })
  }
  // LoadingBar.stop()
});



export default {router,subsetRoutes}
